<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="handleCloseDialog"
    @open="handleOpenDialog"
  >
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <!-- 注意点: el-checkbox收集提交的是label; 文字描述是通过写在双标签内部 -->
      <el-checkbox
        v-for="item in rolesList"
        :key="item.id"
        :label="item.id"
      >{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoleList, reqAssignRoles } from '@/api/setting'
import { reqGetBaseInfo } from '@/api/user'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      checkList: [],
      rolesList: [],
      loading: false
    }
  },
  methods: {
    handleCloseDialog() {
      this.$emit('update:showRoleDialog', false)

      // 优化一个视觉效果: 点击角色, 角色信息跳来跳去
      this.checkList = []
    },
    async getRoleList() {
      const { data: { rows }} = await reqGetRoleList(1, 9999999)
      // console.log(res)
      this.rolesList = rows
      // this.loading = false
    },
    handleOpenDialog() {
      // 表示dialog打开了
      this.loading = true
      // 希望在异步操作之后, 再做某件事 => 封装promise
      // async函数执行默认返回一个promise

      // Promise.all([promise1, pormise2,....]).then(() => {
      // 会在所有的promise成功以后执行
      // })
      // race

      // // 1.获取所有角色列表渲染 (异步)
      // this.getRoleList()
      // // 2.获取员工之前的角色信息 (异步)
      // this.getEmployeeDetail()

      Promise.all([this.getRoleList(), this.getEmployeeDetail()]).then(() => {
        console.log('会在两个请求都成功以后才会执行')
        this.loading = false
      })
    },
    async getEmployeeDetail() {
      // 获取员工之前的角色信息回显
      const { data: { roleIds }} = await reqGetBaseInfo(this.userId)
      // this.loading = false
      // console.log(res)
      this.checkList = roleIds
    },
    async clickSubmit() {
      await reqAssignRoles(this.userId, this.checkList)
      // console.log(res)
      this.$message.success('分配角色成功')
      this.handleCloseDialog()
    }
  }
}
</script>
